package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public R login(LoginInfoVo loginInfoVo) {
        User user = userMapper.selectOne(
                new QueryWrapper<User>().lambda().eq(User::getUserName, loginInfoVo.getUserName())
        );
        if (user == null) {
            return R.ERROR(500, "登录账号错误");
        }
        if (!user.getUserPass().equals(loginInfoVo.getUserPass())) {
            return R.ERROR(500, "登录密码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", user.getUserId())
                .claim("userName", user.getUserName())
                .claim("userMobile", user.getUserMobile())
                .claim("userEmail", user.getUserMobile())
                .claim("nickName", user.getNickName())
                .compact();

        String key = "token" + user.getUserId();

        redisTemplate.opsForValue().set(key, token, 45, TimeUnit.MINUTES);

        user.setUserPass(null);
        user.setToken(token);

        return R.OK(user);
    }
}
